package com.shunhao.base

import android.annotation.TargetApi
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.ViewTreeObserver.OnGlobalLayoutListener
import android.view.WindowManager
import android.view.animation.Animation
import android.view.animation.TranslateAnimation
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import butterknife.ButterKnife
import butterknife.Unbinder
import com.UserManagerCenter.isLogin
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.ObjectUtils
import com.blankj.utilcode.util.ToastUtils
import com.shunhao.event.ILoginCallback
import com.shunhao.model.EventCenter
import com.shunhao.rxlibrary.R
import com.shunhao.utils.BaseAppManager
import com.shunhao.utils.ImmersionBarUtils.initBaseBar
import com.shunhao.utils.LogUtil.i
import com.shunhao.widgets.dialog.ProgressDialogUtil
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*

/**
 * 项目通用父类
 *
 * @author
 */
abstract class BaseActivity : AppCompatActivity() {

    var mContext: Context? = null

    private var mUnBinder: Unbinder? = null
    protected var savedInstanceState: Bundle? = null
    private val compositeDisposable: CompositeDisposable = CompositeDisposable()
    private var isActive = false

    private var mLoginCallback: ILoginCallback? = null

    private var mLlTitleBarLayout: RelativeLayout? = null
    private var mLlContainer: LinearLayout? = null
    private var mLlMoreLayout: LinearLayout? = null
    private var mTvTitle: TextView? = null
    private var mTvRightText: TextView? = null
    private var mIvMoreRight: ImageView? = null
    private var mIvLeftArrow: ImageView? = null
    private var mLlLeft: LinearLayout? = null
    private var mLlBottomLine: LinearLayout? = null

    protected abstract fun isBindEventBusHere(): Boolean

    protected abstract fun getContentViewLayoutId(): Int

    protected abstract fun initViews()

    protected abstract fun initData()

    protected abstract fun onEventComing(eventCenter: EventCenter<Any>)



    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        i(TAG, "[onCreate()] : " + this.javaClass.name)
        this.savedInstanceState = savedInstanceState
        // 竖屏锁定
        //requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        mContext = this
        BaseAppManager.getInstance().addActivity(this)
        //是否绑定了EventBus
        if (isBindEventBusHere()) {
            EventBus.getDefault().register(this)
        }
        // 布局id
        if (getContentViewLayoutId() != 0) {
            setContentView(getContentViewLayoutId())
        } else {
            throw IllegalArgumentException("You must return a right contentView layout resource Id")
        }
        // 初始化黄油刀绑定
        mUnBinder = ButterKnife.bind(this)
        //设置透明状态栏
        initBaseBar(this)
        // 初始化标题栏
        initTitle()
        //TUIKit.addIMEventListener(BaseActivity.mIMEventListener)
        // 一般子类初始化
        initViews()
        // 一般子类业务接口
        initData()
    }


    protected fun initBar() {
        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        BarUtils.setStatusBarColor(this, ContextCompat.getColor(this, R.color.transparent))
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
        }
    }

    override fun onResume() {
        super.onResume()
        isActive = true
    }

    override fun onPause() {
        super.onPause()
        isActive = false
    }

    /**
     * 初始化标题栏
     *
     * @param rightVisible 右边是否显示
     * @param title        标题
     */
    fun setUpTitleBar(rightVisible: Boolean, title: String?) {
        mLlTitleBarLayout = findViewById(R.id.titleBar)
        mLlContainer = findViewById(R.id.ll_title_bar)
        mLlMoreLayout = findViewById(R.id.more_lay)
        mTvTitle = findViewById(R.id.tv_title)
        mIvMoreRight = findViewById(R.id.more_img)
        mLlLeft = findViewById(R.id.ll_left)
        mTvRightText = findViewById(R.id.tv_right_text)
        mIvLeftArrow = findViewById(R.id.iv_left_arrow)
        mLlBottomLine = findViewById(R.id.ll_title_bar_bottom_line)
        // 右边标题栏是否可见
        if (rightVisible) {
            mLlMoreLayout?.visibility = View.VISIBLE
        } else {
            mLlMoreLayout?.visibility = View.INVISIBLE
        }
        if (!ObjectUtils.isEmpty(title)) {
            mTvTitle?.text = title
        }
    }

    /**
     * 设置标题栏右边图片
     *
     * @param drawableId 图标
     */
    protected fun setRightImg(drawableId: Int) {
        if (mLlMoreLayout != null) {
            mLlMoreLayout!!.visibility = View.VISIBLE
        }
        if (mTvRightText != null) {
            mTvRightText!!.visibility = View.GONE
        }
        if (mIvMoreRight != null) {
            if (mIvMoreRight!!.visibility == View.GONE) {
                mIvMoreRight!!.visibility = View.VISIBLE
            }
            // 设置图标
            mIvMoreRight!!.setImageDrawable(ContextCompat.getDrawable(mContext!!, drawableId))
        }
    }

    /**
     * 注册标题栏的返回事件.只有用了include的界面才可以使用.否则抛出异常.
     */
    protected fun registerBackClickEvent() {
        if (mLlLeft != null) {
            mLlLeft!!.setOnClickListener { v: View? -> finish() }
        } else {
            findViewById<View>(R.id.ll_left).setOnClickListener { v: View? -> finish() }
        }
    }

    private fun initTitle() {
        val titleBar = findViewById<RelativeLayout>(R.id.titleBar)
        titleBar?.viewTreeObserver?.addOnGlobalLayoutListener(object : OnGlobalLayoutListener {
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            override fun onGlobalLayout() {
                titleBar.viewTreeObserver.removeOnGlobalLayoutListener(this)
                val ll_left = findViewById<LinearLayout>(R.id.ll_left)
                val more_lay = findViewById<LinearLayout>(R.id.more_lay)
                // 设置左侧按钮宽高
                val lpLeft = ll_left.layoutParams as RelativeLayout.LayoutParams
                lpLeft.width = titleBar.height
                lpLeft.height = lpLeft.width
                ll_left.layoutParams = lpLeft
                // 设置右侧按钮宽高
                val lpMore = more_lay.layoutParams as RelativeLayout.LayoutParams
                lpMore.width = titleBar.height
                lpMore.height = lpMore.width
                more_lay.layoutParams = lpMore
            }
        })
    }

    protected fun addCompositeDisposable(disposable: Disposable?) {
        if (disposable != null) {
            compositeDisposable!!.add(disposable)
        }
    }

    protected fun stopCompositeDisposable(disposable: Disposable?) {
        if (disposable != null && !disposable.isDisposed) {
            disposable.dispose()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    open fun onEventMainThread(eventCenter: EventCenter<Any>?) {
        eventCenter?.let { onEventComing(it) }
    }

    open fun sentEventByEventBus(code: Int) {
        EventBus.getDefault().post(EventCenter<Any>(code))
    }

    fun sentEventByEventBusWithBundle(code: Int, obj: Any?) {
        if (obj == null) {
            sentEventByEventBus(code)
            return
        }
        EventBus.getDefault().post(EventCenter(code, obj))
    }

    override fun finish() {
        super.finish()
        BaseAppManager.getInstance().removeActivity(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        // 如果当前Activity注册了EventBus 则取消注册
        if (isBindEventBusHere()) {
            EventBus.getDefault().unregister(this)
        }
        // 解除黄油刀
        if (mUnBinder != null) {
            mUnBinder!!.unbind()
        }
        //  解除RxJava2的订阅
        if (compositeDisposable != null && !compositeDisposable.isDisposed) {
            compositeDisposable.dispose()
        }
    }


    /**
     * 用户是否登录
     *
     * @return 用户是否登录
     */
    val isUserLogin: Boolean
        get() = isLogin()

    /**
     * 验证是否登录。如果已经登录，则执行callback；否则跳转登录页，登录成功后，执行callback
     *
     * @param callback 是否登录回调
     */
    fun checkLogin(callback: ILoginCallback) {
        if (isUserLogin) {
            callback.onLogin()
        } else {
            // 跳转登录，继续做处理
            mLoginCallback = callback
        }
    }
    /**========================================================工具类方法 */
    /**
     * 提交Post接口 HASH_MAP - JSON
     *
     * @param commitHashMap 键值对数据
     * @return 请求json字符串
     */
    fun getRequestBody2Json(commitHashMap: HashMap<String, Any>): RequestBody {
        val json = GsonUtils.toJson(commitHashMap)
        return json.toRequestBody("application/json".toMediaTypeOrNull())
    }

    /**
     * Toast提示
     *
     * @param message 文本
     */
    protected fun showToast(message: String) {
        ToastUtils.showShort(message)
    }

    /**
     * Toast提示
     *
     * @param msgId 文本id
     */
    protected fun showToast(msgId: Int) {
        ToastUtils.showShort(msgId)
    }

    /**
     * startActivity
     *
     * @param clazz 类
     */
    protected fun readyGo(clazz: Class<*>?) {
        val intent = Intent(this, clazz)
        startActivity(intent)
    }

    /**
     * startActivity with bundle
     *
     * @param clazz  类
     * @param bundle 传递数据对昂
     */
    protected fun readyGo(clazz: Class<*>?, bundle: Bundle?) {
        val intent = Intent(this, clazz)
        if (null != bundle) {
            intent.putExtras(bundle)
        }
        startActivity(intent)
    }

    /**
     * startActivity then finish
     *
     * @param clazz 类
     */
    protected fun readyGoThenKill(clazz: Class<*>?) {
        val intent = Intent(this, clazz)
        startActivity(intent)
        finish()
    }

    /**
     * startActivity with bundle then finish
     *
     * @param clazz  类
     * @param bundle 传递消息对象
     */
    protected fun readyGoThenKill(clazz: Class<*>?, bundle: Bundle?) {
        val intent = Intent(this, clazz)
        if (null != bundle) {
            intent.putExtras(bundle)
        }
        startActivity(intent)
        finish()
    }

    /**
     * startActivityForResult
     *
     * @param clazz       类
     * @param requestCode 请求码
     */
    protected fun readyGoForResult(clazz: Class<*>?, requestCode: Int) {
        val intent = Intent(this, clazz)
        startActivityForResult(intent, requestCode)
    }

    /**
     * startActivityForResult with bundle
     *
     * @param clazz       类
     * @param requestCode 请求码
     * @param bundle      传递对象
     */
    protected fun readyGoForResult(clazz: Class<*>?, requestCode: Int, bundle: Bundle?) {
        val intent = Intent(this, clazz)
        if (null != bundle) {
            intent.putExtras(bundle)
        }
        startActivityForResult(intent, requestCode)
    }

    /**
     * 展示loading框
     */
    fun showLoading() {
        ProgressDialogUtil.getInstance().showProgressDialog(mContext, true)
    }

    /**
     * 展示loading框 自定义文本
     *
     * @param message 自定义文本内容
     */
    fun showLoadingWithText(message: String?) {
        ProgressDialogUtil.getInstance().showProgressDialogMsg(message, mContext, true)
    }

    /**
     * 关闭loading框
     */
    fun hideLoading() {
        ProgressDialogUtil.getInstance().closeProgressDialog()
    }

    companion object {
        /**
         * 日志打印TAG
         */
        private const val TAG = "BaseAppCompatActivity"

        /**
         * 从控件所在位置移动到控件的底部
         *
         * @return
         */
        fun moveToViewBottom(): TranslateAnimation {
            val mHiddenAction = TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                0.0f, Animation.RELATIVE_TO_SELF, 1.0f
            )
            mHiddenAction.duration = 300
            return mHiddenAction
        }

        /**
         * 从控件的底部移动到控件所在位置
         *
         * @return
         */
        fun moveToViewLocation(): TranslateAnimation {
            val mHiddenAction = TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                1.0f, Animation.RELATIVE_TO_SELF, 0.0f
            )
            mHiddenAction.duration = 300
            return mHiddenAction
        }
    }
}